﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Models;
using ConcreteService;
using System.Web;
using Infrastructures;

namespace SponsorshipWeb.Controllers
{
    //  [CommonAuthorize]
    public class EnterpriseController : ApiController
    {
        CompanyService service = ServiceFactory.CreateInstance<CompanyService>();
        ProjectService proService = ServiceFactory.CreateInstance<ProjectService>();
        UtilService utilService = ServiceFactory.CreateInstance<UtilService>();
        AssociationService assoService = ServiceFactory.CreateInstance<AssociationService>();
        UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();

        #region 注册
        /// <summary>
        /// 企业注册填写用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CommonAuthorize]
        [UserRole(APPRole.Company)]
        public IHttpActionResult Create()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest("请登录");
            string respone = "3";
            string userid = user.UserID.ToString();
            var httpPostedForm = HttpContext.Current.Request.Form;

            string name = httpPostedForm["username"];
            var sex = (Sex)Enum.Parse(typeof(Sex), httpPostedForm["sex"], true);
            string phone = httpPostedForm["phone"];
            string qq = httpPostedForm["qq"];
            string wechart = httpPostedForm["wechart"];
            string email = httpPostedForm["email"];
            string role = httpPostedForm["Role"];

            var userinfo = service.Get<UserInfo>(userid);

            userinfo.Phone = phone;
            userinfo.NickName = name;
            userinfo.QQ = qq;
            userinfo.Sex = sex;
            userinfo.WeChart = wechart;
            userinfo.Email = email;
            userinfo.Role = APPRole.Company;
            userinfo.Status = CommonStatus.ThirdStep;

            if (!role.IsNullOrEmpty() && role == "Company")
            {
                var enumRole = (APPRole)Enum.Parse(typeof(APPRole), role, true);
                respone = "4";
                userinfo.Role = enumRole;
            }

            service.Update(userinfo, userid);
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = respone
            });
        }

        /// <summary>
        /// 企业注册最后一步，提交各种照片
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Company)]
        public IHttpActionResult CreateMainMes()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            int userid = user.UserID;

            var httpPostedFile = HttpContext.Current.Request.Files;
            var httpPostedForm = HttpContext.Current.Request.Form;


            HttpPostedFile License = httpPostedFile["License"];

            FileUtil.SaveFile(License, FileType.License, userid, userid.ToString(), APPRole.Company);

            #region seldomused
            string LDID = httpPostedForm["LDID"];
            string AliPayNo = httpPostedForm["AliPayNo"];
            string BankNo = httpPostedForm["BankNo"];

            var lstse = utilService.ListSeldomUsed(userid, SeldomType.All, APPRole.Company);
            SeldomUsed se1 = new SeldomUsed(userid, APPRole.Company, SeldomType.PersonCardNo, LDID);
            SeldomUsed se2 = new SeldomUsed(userid, APPRole.Company, SeldomType.AliPayNo, AliPayNo);
            SeldomUsed se3 = new SeldomUsed(userid, APPRole.Company, SeldomType.BankNo, BankNo);

            var existSe1 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.PersonCardNo).FirstOrDefault();
            var existSe2 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.AliPayNo).FirstOrDefault();
            var existSe3 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.BankNo).FirstOrDefault();

            if (existSe1 == null)
            {
                utilService.CreateSeldomUsed(se1, userid.ToString());
            }
            else
            {
                existSe1.Value = LDID;
                utilService.UpdateSeldomUsed(existSe1, userid.ToString());
            }
            if (existSe2 == null)
            {
                utilService.CreateSeldomUsed(se2, userid.ToString());
            }
            else
            {
                existSe2.Value = AliPayNo;
                utilService.UpdateSeldomUsed(existSe2, userid.ToString());
            }
            if (existSe3 == null)
            {
                utilService.CreateSeldomUsed(se3, userid.ToString());
            }
            else
            {
                existSe3.Value = BankNo;
                utilService.UpdateSeldomUsed(existSe3, userid.ToString());
            }
            #endregion

            UserInfo userinfo = userService.Get<UserInfo>(userid.ToString());
            userinfo.Status = CommonStatus.FiveStep;
            userService.Update(userinfo, userid.ToString());
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "5"
            });
        }

        /// <summary>
        /// 创建企业负责人信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Company)]
        public IHttpActionResult CreateOrUpdate()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userID = user.UserID.ToString();

            var httpPostedForm = HttpContext.Current.Request.Form;

            var userinfo = userService.Get<UserInfo>(userID);

            string name = httpPostedForm["name"];
            string chargeName = httpPostedForm["chargeName"];
            string jobType = httpPostedForm["jobType"];
            string sign = httpPostedForm["sign"];
            string type = httpPostedForm["type"];
            string size = httpPostedForm["size"];
            string href = httpPostedForm["href"];
            string address = httpPostedForm["address"];
            string from = httpPostedForm["from"];

            #region Company

            Company obj = new Company
            {
                CompanyNO = userID.ToInt(),
                Name = name,
                ChargeName = chargeName,
                TypeNO = type.ToInt(),
                Sign = sign,
                SizeNO = size.ToInt(),
                CompanyHref = href,
                Address = address,
                UpdateTime = DateTime.Now,
                Status = CommonStatus.Pending,
                JobTypeNO = jobType.ToInt()
            };
            #endregion

            if (from.IsNullOrEmpty())
            {
                #region file
                var httpPostedFile = HttpContext.Current.Request.Files;
                HttpPostedFile logo = httpPostedFile[0];
                string path = FileUtil.SaveFile(logo, FileType.CompanyLogo, obj.CompanyNO, userID, APPRole.Company);
                obj.LogoPath = path;
                #endregion

                userinfo.Status = CommonStatus.FourStep;
                userinfo.HeadImage = path;
                userService.Update(userinfo, userID);
            }
            var exist = service.Get<Company>(obj.CompanyNO.ToString());
            if (exist == null)
            {
                obj.CreateTime = DateTime.Now;
                service.Create<Company>(obj, userID);
                //utilService.SpliteWord(SpliteWordFun.Company, obj.CompanyNO, obj.Name);
            }
            else
            {
                exist.Name = name;
                exist.ChargeName = chargeName;
                exist.TypeNO = type.ToInt();
                exist.Sign = sign;
                exist.SizeNO = size.ToInt();
                exist.CompanyHref = href;
                exist.Address = address;
                exist.UpdateTime = DateTime.Now;
                exist.JobTypeNO = jobType.ToInt();
                service.Update(exist, userID);
            }

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "3"
            });
        }

        #endregion

        #region 获取企业信息
        /// <summary>
        /// 获取企业首页信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [CommonAuthorize]
        [UserRole(APPRole.Company)]
        public IHttpActionResult GetCompany()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            int userID = user.UserID;
            var obj = service.GetCompany(userID.ToString());
            var userinfo = userService.Get<UserInfo>(userID.ToString());
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (obj != null)
                dic = obj.ToDictionary();

            dic.AddOrReplace("Status", userinfo.Status.ToString());
            dic.AddOrReplace("LogoPath", SystemConfig.Get("UploadHttpPath") + userinfo.HeadImage);

            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }

        /// <summary>
        /// 获取企业负责人信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Company)]
        public IHttpActionResult GetInCharge()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest("请登录");
            int userid = user.UserID;
            var userinfo = userService.Get<UserInfo>(userid.ToString());
            var company = service.Get<Company>(userid.ToString());
            var dic = userinfo.ToDictionary();
            if (company != null)
                dic.Add("ChargeName", company.ChargeName);
            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });

        }

        #endregion

        #region 更新企业信息

        /// <summary>
        /// 更新企业信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Company)]
        public IHttpActionResult UpdateCompany()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            int userid = user.UserID;

            var httpPostedFile = HttpContext.Current.Request.Files;
            var httpPostedForm = HttpContext.Current.Request.Form;

            string name = httpPostedForm["name"];
            string sex = httpPostedForm["sex"];
            string phone = httpPostedForm["phone"];
            string qq = httpPostedForm["qq"];
            string wechart = httpPostedForm["wechart"];
            string email = httpPostedForm["email"];
            var userinfo = userService.Get<UserInfo>(userid.ToString());
            userinfo.Phone = phone;
            userinfo.QQ = qq;
            userinfo.Sex = (Sex)Enum.Parse(typeof(Sex), sex, true);
            userinfo.WeChart = wechart;
            userinfo.Email = email;
            userinfo.Status = CommonStatus.FiveStep;

            userService.Update(userinfo, userid.ToString());

            HttpPostedFile License = httpPostedFile["License"];

            if (License.ContentLength != 0)
                FileUtil.SaveFile(License, FileType.License, userid, userid.ToString(), APPRole.Company);

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "OK"
            });
        }

        #endregion

        [UserRole(APPRole.Company)]
        public IEnumerable<Project> Get()
        {
            LoginInfo user = AuthUtil.GetAuthentication();
            return null;
        }

        [UserRole(APPRole.Company)]
        public IHttpActionResult GetCompany([FromUri]string id)
        {
            Company company = service.Get<Company>(id);

            return Ok(new ObjectResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseObj = company
            });
        }
        // GET api/enterprise/5
        [UserRole(APPRole.Company)]
        public IHttpActionResult Get(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
                return BadRequest("公司编号为空");

            LoginInfo user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();

            //if (user.CompanyID == 0)
            //    return null;

            //Company company = service.Get<Company>(user.CompanyID.ToString());

            //if (company == null)
            //    return NotFound();

            //if (company.ContactNO != user.UserID)
            //    return null;


            //return Ok(new ObjectResponse()
            //{
            //    Status = ResponseStatus.OK(),
            //    ResponseObj = company
            //});
            return null;
        }

        [UserRole(APPRole.Company)]
        [HttpGet]
        public IHttpActionResult ListAccountInfo()
        {
            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = new List<Object>()
            });
        }
    }
}
